package com.example.systemserver.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWTUtil;
import com.example.systemserver.bean.AccountBean;
import com.example.systemserver.config.MyException;
import com.example.systemserver.mapper.AccountMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Slf4j
@Service
public class AccountService {
    @Resource
    private AccountMapper accountMapper;
    public String login(AccountBean bean) {
        log.debug("登录(检查参数)");
        if (bean == null) {
            throw new MyException("参数异常");
        }
        if (bean.getUsername() ==null || bean.getUsername().trim().isEmpty()) {
            throw new MyException("用户名不能为空");
        }
        if (bean.getPassword() ==null || bean.getPassword().trim().isEmpty()) {
            throw new MyException("密码不能为空");
        }


        log.debug("登录(查询用户)");
        AccountBean accountBean = accountMapper.info(bean);
        if (accountBean == null){
            throw new MyException("用户名密码不存在");
        }
        String md5 = DigestUtil.md5Hex(bean.getPassword());
        if (!md5.equals(accountBean.getPassword())){
            throw new MyException("用户名密码不存在");
        }

        log.debug("用户登录成功(返回token值)");
        //jwt<jwe,jws>
        //{加密属性（加密算法，长度等）,载荷（payload）,签名}
        HashMap<String,Object> map = new HashMap<>();
        map.put("timeout",System.currentTimeMillis()+24*60*60*1000);
        map.put("id",accountBean.getId());
        String token = JWTUtil.createToken(map, "123456".getBytes(StandardCharsets.UTF_8));
        return  token;

    }

    public static void main(String[] args) {
        String username = "bailu666";
        String md5 = DigestUtil.md5Hex(username);
        System.out.println(md5);

    }
}
